package com.ls.user.controller;

import com.ls.common.entity.Result;
import com.ls.common.util.JwtUtil;
import com.ls.user.pojo.dto.LoginDTO;
import com.ls.user.pojo.entity.User;
import com.ls.user.pojo.entity.UserScore;
import com.ls.user.service.IUserScoreService;
import com.ls.user.service.IUserService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author xiaotang
 * @since 2023-04-07
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    IUserService userService;

    @Autowired
    IUserScoreService userScoreService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @PostMapping("/addOrUpdateUserScore")
    @ApiOperation("添加或者修改用户积分")
    public Result addOrUpdateUserScore(@RequestBody UserScore userScore){
        Boolean flag = userScoreService.saveOrUpdate(userScore);
        return flag ? new Result(200, "操作成功") : new Result(500, "操作失败");
    }

    @GetMapping("/getScoreByUserId/{userId}")
    @ApiOperation("根据用户id查询用户积分")
    public Result getScoreByUserId(@PathVariable Integer userId){
        UserScore userScore = userScoreService.getScoreByUserId(userId);
        return new Result(200, "查询成功", userScore);
    }


    @GetMapping("/getUserInfo/{id}")
    @ApiOperation("获取用户信息")
    public Result getUserInfo(@PathVariable Integer id){
        User user = userService.getById(id);
        return new Result(200, "success", user);
    }

    @PostMapping("/login")
    @ApiOperation("登陆")
    public Result login(@RequestBody LoginDTO loginDTO){
        Assert.notNull(loginDTO, "登陆参数为空");
        User user = userService.login(loginDTO);
        if(user == null){
            return new Result(500, "用户名密码错误");
        }
        Map<String, Object> jwtMap = new HashMap<>();
        jwtMap.put("username", user.getUsername());
        String jwtToken = JwtUtil.createJWT(user.getId().toString(), jwtMap, 1000 * 60 * 3L);
        redisTemplate.opsForValue().set("mall-parent:login:" + jwtToken, jwtToken);
        return new Result(200, "登陆成功", jwtToken);
    }

    @DeleteMapping("/removeUser/{id}")
    @ApiOperation("删除用户")
    public Result removeUser(@PathVariable Integer id){
        boolean b = userService.removeById(id);
        return b == true ? new Result(200, "删除成功") : new Result(500, "删除失败");
    }

    @PostMapping("addOrUpdateUser")
    @ApiOperation("添加用户或者修改用户")
    public Result addUser(@RequestBody LoginDTO loginDTO){
        User user = new User();
        BeanUtils.copyProperties(loginDTO, user);
        Boolean flag = userService.saveOrUpdate(user);

        return flag ? new Result(200, "操作成功") : new Result(500, "操作失败");
    }

}
